package cn.jhc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;

import cn.jhc.Global;
import cn.jhc.bean.Article;
import cn.jhc.db.ArticleDao;

/**
 * Servlet implementation class ListArticlesServlet
 */
@WebServlet("/admin/list.do")
public class ListArticlesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 * 需要的数据：
	 * 1.当前页码
	 * 2.总页数
	 * 3.文章列表
	 */
	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type");
		if( type == null) {
			type = "html";
		}
		
		String pageNum = request.getParameter("page");
		int currentPage = 0;
		if(pageNum != null) {
			try {
				currentPage = Integer.valueOf(pageNum).intValue();
			} catch (NumberFormatException e) {
				e.printStackTrace();
				currentPage = 0;
			}
		}
		
		
		QueryRunner runner = (QueryRunner) request.getServletContext().getAttribute(Global.KEY_QUERY_RUNNER);
		List<Article> articles = null;
		long count = 0;
		try {
			articles = ArticleDao.find(runner, 0);
			count = ArticleDao.count(runner);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		long total = count % Global.PAGE_SIZE == 0 ? count / Global.PAGE_SIZE : 
			count / Global.PAGE_SIZE + 1;
		
		if( type.equals("html")) {
		// 两种解决方案：一种是 sesstion + redirect , 二是 request + forward
		// 方案一 ： 两个来回
//		request.getSession().setAttribute("articles", articles);
//		response.sendRedirect("./list.jsp");
		
		// 方案二 ： 一个来回
		request.setAttribute("articles", articles);
		request.setAttribute("currentPage", currentPage);
		request.setAttribute("total", total);
		
		request.getRequestDispatcher("./list.jsp").forward(request, response);
		} else if(type.equals("json")) {
			request.setAttribute("currentPage", currentPage);
			request.setAttribute("total", total);
			response.setContentType("application/json; charset=utf8");
			JsonArrayBuilder builder = Json.createArrayBuilder();
			for( Article article : articles) {
				builder.add(article.toJson());
			}
			PrintWriter writer = response.getWriter();
			writer.print(builder.build().toString());
		}
		
	
	}

	

}
